package com.zb.hello.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zb.hello.util.Docx4jUtil;

@Controller
@RequestMapping("/test")
public class Docx4jTest {
	
	@RequestMapping("/downloadword")
	@ResponseBody
	public byte[] downloadWord() throws Docx4JException, JAXBException, FileNotFoundException {
		//模板文件路径
		String path = this.getClass().getClassLoader().getResource("template/test.docx").getPath();
		//模板中要生成表格的数据
		List<Map<String, String>> list = new ArrayList<>();
		for (int i = 0; i < 3; i++) {
			Map<String, String> m = new HashMap<>();
			m.put("name", "姓名"+i);
			m.put("sex", "性别"+i);
			m.put("age", "年龄"+i);
			m.put("bz", "备注"+i);
			m.put("xx", "详细"+i);
			list.add(m);
		}
		list.stream();
		
		//模板中要插入图片的数据
		byte[] img = null;
		try (InputStream input = new FileInputStream(this.getClass().getClassLoader().getResource("template/timg.jpg").getPath())){
			 img = new byte[input.available()];
			input.read(img);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//要插入的map数据
		Map<String, String> m = new HashMap<>();
		m.put("today", LocalDate.now().toString());
		m.put("active", "游泳");
		
		//处理好数据后就是超级简单的调用
		return Docx4jUtil.of(path)
				         .addParam("title", "测试文档标题")
				         .addParam("user", "测试人")
				         .addParams(m)
				         .addTable("name", 2, list)
				         .addImg("img", img)
				         .get();
	}

}
